<template>
  <el-card>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>

      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input placeholder="请输入内容" clearable @clear="getUserList" v-model="queryInfo.query">
          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="addDialogVisible=!addDialogVisible">添加用户</el-button>
      </el-col>
    </el-row>
    <el-table :data="userList" border style="width: 100%" stripe>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="userName" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <!-- 身份列 -->
      <el-table-column label="身份">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.role=='admin'">超级管理员</el-tag>
          <el-tag v-if="scope.row.role=='normal'" type="success">普通用户</el-tag>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.userId)"
          ></el-button>

          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteUserById(scope.row.userId)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加用户用到的模态框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password1">
          <el-input v-model="addForm.password1"></el-input>
        </el-form-item>
        <el-form-item label="身份" prop="role">
          <el-select v-model="addForm.role" placeholder="请选择身份">
            <el-option label="普通用户" value="normal"></el-option>
            <el-option label="超级管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog @close="editDialogClose" title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form label-width="100px" :model="editForm" :rules="addFormRules" ref="editForm">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="身份" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择身份">
            <el-option label="普通用户" value="normal"></el-option>
            <el-option label="超级管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>
<script>
export default {
  // eslint-disable-next-line space-before-function-paren
  data() {
    // 验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证邮箱规则
    var checkPassword = (rule, value, cb) => {
      // 验证邮箱的正则表达式

      if (value === this.addForm.password) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('两次输入的密码不一致'))
    }
    return {
      // 用户列表
      userList: [],
      queryInfo: {
        query: ''
      },
      // 添加用户用到的模态框的状态控制
      addDialogVisible: false,
      // 修改用户用到的模态框的状态控制
      editDialogVisible: false,
      // 添加用户用到的表单
      addForm: {
        email: '',
        userName: '',
        // 身份
        role: '',
        password: '',
        // 确认密码
        password1: ''
      },
      // 修改用户用到的表单
      editForm: {
        userId: '',
        email: '',
        userName: '',
        // 身份
        role: ''
      },
      // 添加用户用到的验证规则
      addFormRules: {
        // 邮箱的验证规则
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在3到10之间', trigger: 'blur' }
        ],
        role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6到15之间', trigger: 'blur' }
        ],
        password1: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6到15之间', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ]
      }
    }
  },
  // eslint-disable-next-line space-before-function-paren
  created() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    // eslint-disable-next-line space-before-function-paren
    async getUserList() {
      const { data: res } = await this.$http.get(
        '/api/users?name=' + this.queryInfo.query
      )
      //  console.log(res.Table)
      this.userList = res.Table
    },
    // 添加用户对话框的确定键
    // eslint-disable-next-line space-before-function-paren
    async addUser() {
      this.addDialogVisible = false
      // console.log(this.addForm)
      // 将数据发送到后台
      var params = new URLSearchParams()
      params.append('email', this.addForm.email)
      params.append('userName', this.addForm.userName)
      params.append('role', this.addForm.role)
      params.append('password', this.addForm.password)

      const { data: res } = await this.$http({
        method: 'post',
        url: 'api/users',
        data: params,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      })
      console.log(res)
      if (res.status !== 200) return this.$message.error('添加用户失败')
      this.$message.success('添加用户成功')
      this.getUserList()
    },
    // 当添加用户的模态框关闭的时候
    // eslint-disable-next-line space-before-function-paren
    addDialogClose() {
      // 重置表单
      this.$refs.addForm.resetFields()
    },
    // 点击删除按钮
    // eslint-disable-next-line space-before-function-paren
    async deleteUserById(id) {
      const removeUserById = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(removeUserById)
      // console.log(id)
      // 取消了删除
      if (removeUserById !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      console.log(id)
      const { data: res } = await this.$http.post('api/users?value=' + id)
      console.log(res)

      if (res.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    // 点击编辑按钮
    // eslint-disable-next-line space-before-function-paren
    async showEditDialog(id) {
      this.editDialogVisible = true
      // console.log(id)

      // 发送请求获取数据
      const { data: res } = await this.$http.get('/api/users/' + id)
      this.editForm.userId = id
      this.editForm.email = res.Table[0].email
      this.editForm.userName = res.Table[0].userName
      this.editForm.role = res.Table[0].role
      console.log(res)
    },
    // 点击编辑按钮
    // eslint-disable-next-line space-before-function-paren
    editDialogClose() {
      this.$refs.editForm.resetFields()
    },
    // 点击编辑对话框中的确定按钮
    // eslint-disable-next-line space-before-function-paren
    async editUser() {
      const data = await this.$http.get('/api/users/', {
        params: {
          id: this.editForm.userId,
          userName: this.editForm.userName,
          email: this.editForm.email,
          role: this.editForm.role
        }
      })
      console.log(data)
      this.$message.success('修改成功')
      this.editDialogVisible = false
      this.getUserList()
    }
    // eslint-disable-next-line space-before-function-paren
    // deleteUser(id) {}
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin-bottom: 20px;
}
</style>
